# This Module Provide all Tools in Project
import os
import sys
import csv
import json
import time
import logging
from configparser import ConfigParser

def CSVReader(file=r'../Data/testPointDetails.csv', firstline=False) ->list:
    '''
    A Function for CSV File read
    :param file: The CSV File Which U Wanna Parser and Store
    :param firstline: Bool() Type， If True, Return Contains CSV File Header
    :return: List contains Tuple, Including 5 items
    '''
    list = []

    try:
        file = open(file, 'r', encoding='UTF-8')
        file.close()
    except:
        file = r'Data/testPointDetails.csv'

    with open(file,'r',encoding='utf-8') as file:
        items = csv.reader(file)
        for item in items:
            list.append(tuple(item[i] for i in range(5)))
        if not firstline:
            list.pop(0)
    return list

def JSONReader(keyword:str, file=r'../Config/information.json'):
    '''
    Using Deal Information via Json Loads
    :param keyword: Parser Key Like 'menu','market','deal','type_'
    :param file: None
    :return: List
    '''
    try:
        file = open(file, 'r', encoding='UTF-8')
        file.close()
    except:
        file = r'Config/information.json'

    with open(file, 'r', encoding='UTF-8') as file:
        data = json.loads(file.read())
        if keyword == 'all':
            return data
        else:
            return data.get(keyword)

def INIReader(section:str, key:str, file=r'../Config/config.ini'):
    '''
    All Configuration File Saved in r'../Config/config.ini'
    :param section: SECTION in configFileXXX.ini
    :param key: key in configFileXXX.ini
    :param file: None
    :return: A Value locator by Key
    '''

    try:
        file = open(file, 'r', encoding='UTF-8')
        file.close()
    except:
        file = r'Config/config.ini'

    config = ConfigParser()
    config.read(file)
    return config.get(section, key)

class LOG:

    def __init__(self):
        # Delete Log Directory Log File
        os.makedirs(INIReader('LOG', 'logpath'), exist_ok=True)
        list = sorted(os.listdir(INIReader('LOG', 'logpath')), reverse=True)
        if len(list) >= 6:
            os.remove(os.path.join(INIReader('LOG', 'logpath'),list[-1]))
        logging.basicConfig(format='%(asctime)s %(name)s [Line: %(lineno)d] %(message)s',
                            level=logging.DEBUG,
                            filename=r'Log/log_%s.log' % time.strftime('%Y%m%d_%H%M%S', time.localtime()),
                            filemode='w',
                            )
        self.logging = logging

    def DEBUG(self, messages):
        self.logging.debug(messages)

    def info(self, messages):
        self.logging.info(messages)

    def WARNING(self, messages):
        self.logging.warning(messages)

    def ERROR(self, messages):
        self.logging.error(messages)


if __name__ == '__main__':
    # for schema in CSVReader():
    #     print(schema)
    # print(JSONReader('all'))
    print(INIReader('EXCEL','excelpath'))
    print(JSONReader('market'))
    LOG().DEBUG('调试信息123')
    # logging.debug('调试信息')
